package com.yksj.healthtalk.ui.doctorstation;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.DcotorServiceManagerEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.SettingManager;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 医生设置
 * 
 * @author jack_tang
 * 
 */
public class DoctorSettingActivity extends BaseFragmentActivity implements
		OnClickListener, OnCheckedChangeListener {
	
	private ToggleButton mDistractionFreeZone;// 免打扰开关
	private String mData;
	private LinearLayout mView;
	private ToggleButton mToggleButtonSound;//短信免打扰开关
	@Override
	protected void onCreate(Bundle save) {
		super.onCreate(save);
		if(save != null){
			mData = save.getString("mData");
		}
		setContentView(R.layout.doctor_setting);
		initView();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent =new Intent(this,CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		startService(intent);
	}
	
	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("服务设置");
		mToggleButtonSound = (ToggleButton) findViewById(R.id.sound_open);
		mDistractionFreeZone = (ToggleButton)findViewById(R.id.distraction_free_zone);
		if(mData != null){
			onParseData(mData);
		}else{
			initSeachData();
		}
	}
	
	private void initSeachData() {
		HttpRestClient.doHttpDoctorSettingUI(new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				onParseData(content);
			}
		});
	}
	
	private void onParseData(String content){
		try {
			JSONArray array=new JSONArray(content);
			List<DcotorServiceManagerEntity> entitys = new ArrayList<DcotorServiceManagerEntity>();
			for (int i = 0; i < array.length(); i++) {
				JSONObject object=(JSONObject) array.get(i);
				if(object.has("REMIND_ON_OFF")){
				int str=object.optInt("REMIND_ON_OFF",0);
				mDistractionFreeZone.setChecked(str==1);	
				int str2=object.optInt("SMS_ON_OFF",0);
				mToggleButtonSound.setChecked(str2==1);	
				}else{
					DcotorServiceManagerEntity entity=new DcotorServiceManagerEntity(); 
					entity.setOPEN_FLAG(object.optString("OPEN_FLAG"));
					entity.setSERVICE_TYPE(object.optString("SERVICE_TYPE"));
					entity.setSERVICE_TYPE_ID(object.optString("SERVICE_TYPE_ID"));
					entity.setISOPEN(object.optString("ISOPEN"));
					entitys.add(entity);	
				}
			}
			initDataView(entitys);
		} catch (Exception e) {
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("mData", mData);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return ;
		switch (requestCode) {
		case 1000:
			if(data!=null&&data.hasExtra("isUpdate")){
				mView.removeAllViews();
				initSeachData();
			}
			break;
		}
	}
	
	private void initDataView(final List<DcotorServiceManagerEntity> entitys){
		LinearLayout linelayout = new LinearLayout(this);
		linelayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
		linelayout.setOrientation(LinearLayout.VERTICAL);
		int size=entitys.size();
		for (int i = 0; i <size; i++) {
			View view = LayoutInflater.from(this).inflate(R.layout.doctor_base_add_view_item, null);
			TextView name = (TextView) view.findViewById(R.id.name);
			TextView status = (TextView) view.findViewById(R.id.status);
			final DcotorServiceManagerEntity entity = entitys.get(i);
			name.setText(entity.getSERVICE_TYPE());
			
			if(entity.getISOPEN().equals("1"))
			status.setText("已开通");
			else
			status.setText("未开通");
			
			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(entity.getOPEN_FLAG().equals("0"))return;
					Intent intent;
					if("1".equals(entity.getSERVICE_TYPE_ID())){// 普通咨询
						httpRespon(entity.getSERVICE_TYPE_ID(),entity.getSERVICE_TYPE());
					}else{// 预约时段咨询
						intent = new Intent(DoctorSettingActivity.this, DoctorMarkTalkFragment.class);
						intent.putExtra("SERVICE_TYPE_ID", entity.getSERVICE_TYPE_ID());
						intent.putExtra("SERVICE_TYPE_NAME", entity.getSERVICE_TYPE());
						startActivityForResult(intent,1000);
					}
				}
			});
			
			if (i== 0) {
				view.setBackgroundResource(R.drawable.textview_background_up);
			} else if (i == size-1) {
				view.setBackgroundResource(R.drawable.textview_background_down);
			} else {
				view.setBackgroundResource(R.drawable.textview_background_middle);
			}
			linelayout.addView(view);
		/*	if(i!=size-1){
				LinearLayout line=new LinearLayout(this);
				line.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,2));
				line.setBackgroundResource(R.drawable.divider_horizontal_timeline);
				linelayout.addView(line);
			}*/
			
		}
		SettingManager.getInstance().setServiceNote(mDistractionFreeZone.isChecked());
		mView = (LinearLayout) findViewById(R.id.line);
		mView.addView(linelayout);
		mDistractionFreeZone.setOnCheckedChangeListener(this);
		mToggleButtonSound.setOnCheckedChangeListener(this);
	}

	protected void httpRespon(final String id,final String title) {
		HttpRestClient.doHttpDoctorMarkCommon(id,
				new ObjectHttpResponseHandler(this) {
			@Override
			public Object onParseResponse(String content) {
				return content;
			}
			@Override
			public void onSuccess(Object response) {
				super.onSuccess(response);
				if(response==null)return;
				Intent intent=new Intent(DoctorSettingActivity.this,DoctorMarkCommon.class);
				intent.putExtra("SERVICE_TYPE_ID", id);
				intent.putExtra("CONTENT", response.toString());
				intent.putExtra("title", title);
				startActivityForResult(intent, 1000);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		}

	}


	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.sound_open:// 短信免打扰
		{
			RequestParams params = new RequestParams();
			params.put("Type", "updateCustomerinfoServiceSetduanxin");
			params.put("CUSTOMER_ID", SmartFoxClient.getLoginUserId());
			if(isChecked){
				params.put("SMS_ON_OFF", "1");
			}else{
				params.put("SMS_ON_OFF", "0");
			}
			HttpRestClient.doHttpServiceSetServletRJ320(params,new AsyncHttpResponseHandler(this){
				@Override
				public void onStart() {
					super.onStart();
					mToggleButtonSound.setEnabled(false);
				}
				@Override
				public void onFinish() {
					super.onFinish();
					mToggleButtonSound.setEnabled(true);
				}
				
				@Override
				public void onSuccess(String content) {
					super.onSuccess(content);
					try {
						JSONObject jsonObject=new JSONObject(content);
						if(jsonObject.has("error_message")){
							ToastUtil.showBasicShortToast(DoctorSettingActivity.this,jsonObject.getString("error_message"));
						}else{
							ToastUtil.showBasicShortToast(DoctorSettingActivity.this,"修改成功...");
						}
					} catch (Exception e) {
					}
				}
			});
		}
			break;
		case R.id.distraction_free_zone:
		{
			SettingManager.getInstance().setServiceNote(mDistractionFreeZone.isChecked());
			HttpRestClient.doHttpDoctorFree_zone(isChecked,new AsyncHttpResponseHandler(this){
			
				@Override
				public void onSuccess(String content) {
					super.onSuccess(content);
					try {
						JSONObject jsonObject=new JSONObject(content);
						if(jsonObject.has("error_message")){
							mDistractionFreeZone.setChecked(mDistractionFreeZone.isChecked());
							ToastUtil.showBasicShortToast(DoctorSettingActivity.this,jsonObject.getString("error_message"));
						}else{
							ToastUtil.showBasicShortToast(DoctorSettingActivity.this,"修改成功...");
						}
						
					} catch (Exception e) {
					}
				}
			});}
			break;
		}
	}
}
